package com.gitee.qdbp.base.orm.mybatis.converter;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.alibaba.fastjson.JSON;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * JSON格式转换
 *
 * @author zhaohuihua
 * @version 151125
 */
public class JsonMapTypeHandler extends BaseTypeHandler<Map<String, Object>> {

    public JsonMapTypeHandler(Class<?> type) {
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toJsonObject(rs.getString(columnName));
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toJsonObject(rs.getString(columnIndex));
    }

    @Override
    public Map<String, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toJsonObject(cs.getString(columnIndex));
    }

    private Map<String, Object> toJsonObject(String string) {
        if (VerifyTools.isBlank(string)) {
            return null;
        }

        return JSON.parseObject(string);
    }
}
